import {parseHTML} from "./parse";

export function compileToFunction(template) {
//     生成ast
    let ast = parseHTML(template)
//     树转换
    let code = codegen(ast);
    code = `with(this){return ${code}}`
    return new Function(code);
}
// 代码生成
function codegen(ast) {
    let children = genChildren(ast);

    let code = `_c('${ast.tag}',${ast.attrs.length > 0 ? genProps(ast.attrs) : 'null'}${ast.children.length > 0 ?`,${children}`:''})`

    return code;
}
function genProps(attrs) {
    let str = ""
    for (let i = 0; i < attrs.length; i++) {
        let attr = attrs[i]
        if (attr.name === 'style') {
            let obj = {}
        //     color: red; width: '100px'
            attr.value.split(";").forEach(item => {
                let [key, value] = item.split(":")
                obj[key] = value
            })
            attr.value = obj
        }
        str += `${attr.name}:${JSON.stringify(attr.value)},`
    }
    return `{${str.slice(0,-1)}}`
}

function genChildren(ele) {
    const children = ele.children
    if(children) {
        return children.map(child => gen(child)).join(',')
    }
}
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g
function gen(node) {
    // 判断是文本还是元素
    if(node.type === 1) {
        return codegen(node)
    }else {
        // 文本
        let text = node.text
        if(!defaultTagRE.test(text)) {
            return `_v(${JSON.stringify(text)})`
        } else {
            let tokens = []
            let match
            defaultTagRE.lastIndex = 0
            let lastIndex = 0
            while(match = defaultTagRE.exec(text)) {
                let index = match.index
                if(index > lastIndex) {
                    tokens.push(JSON.stringify(text.slice(lastIndex, index)))
                }
                tokens.push(`_s(${match[1].trim()})`)
                lastIndex = index + match[0].length
            }
            if(lastIndex < text.length) {

                tokens.push(JSON.stringify(text.slice(lastIndex)))
            }

            return `_v(${tokens.join('+')})`
        }
    }
}